package com.quectel.taskserver.job.warnhousehold;

import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.business.common.parking.CarAccessLimitBusiness;
import com.quectel.constant.core.PreWarnConstants;
import com.quectel.core.module.prewarning.dto.PreWarningRecordDto;
import com.quectel.core.module.prewarning.service.PreWarningRecordService;
import com.quectel.util.kit.PageFetchKit;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shardingsphere.elasticjob.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.simple.job.SimpleJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 在这里编写说明
 *
 * @author: ryan
 * @email: ryan.ran@quectel.com
 * @date: 2023-06-02 17:09:00
 */
@Component
public class CarAccessWarnUpholdTask implements SimpleJob {
    @Autowired
    private CarAccessLimitBusiness carAccessLimitBusiness;
    @DubboReference
    private PreWarningRecordService preWarningRecordService;

    @Override
    public void execute(ShardingContext shardingContext) {
        uphold();
    }

    private void uphold() {
        Map<String, Object> params = new HashMap<>();
        params.put(LambdaUtil.getFieldName(PreWarningRecordDto::getPreWarnType), PreWarnConstants.AlarmTypeEnum.CAR_RECORD_TOO_MANY.getType());
        List<PreWarningRecordDto> preWarningRecordDtos = PageFetchKit.fetchAll(req -> preWarningRecordService.queryList(req), params, 500);

        for (PreWarningRecordDto preWarningRecordDto : preWarningRecordDtos) {
            boolean exceedingLimit = carAccessLimitBusiness.isExceedingLimit(preWarningRecordDto.getVillageId()
                    , preWarningRecordDto.getLicenseColor(), preWarningRecordDto.getLicense());
            if (exceedingLimit) {
                Long items = carAccessLimitBusiness.getItems(preWarningRecordDto.getVillageId()
                        , preWarningRecordDto.getLicenseColor(), preWarningRecordDto.getLicense());
                if (!preWarningRecordDto.getDiffValue().equals(items.toString())) {
                    PreWarningRecordDto newlyDto = new PreWarningRecordDto();
                    newlyDto.setId(preWarningRecordDto.getId());
                    newlyDto.setDiffValue(items.toString());
                    preWarningRecordService.updateById(newlyDto);
                }
            } else {
                preWarningRecordService.clean(preWarningRecordDto.getId());
            }
        }
    }
}
